package com.tqz.web.flux.demo.service;

import com.tqz.web.flux.demo.dao.UserDao;
import com.tqz.web.flux.demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.util.function.Function;

/**
 * <p>
 *
 * @author tianqingzhao
 * @since 2023/3/5 20:14
 */
@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    public Mono<User> saveOrUpdate(User user) {
        return userDao.save(user);
    }

    public Mono<Void> deleteById(Integer id) {
        return oper(id, id, userDao::deleteById);
    }

    public Mono<User> updateUser(User user) {
        if (user == null) {
            return Mono.empty();
        }

        return oper(user.getId(), user, userDao::save);
    }

    public Mono<User> getById(Integer id) {
        return oper(id, id, userDao::findById);
    }

    private <R, T> Mono<R> oper(Integer id, T value, Function<T, ? extends Mono<? extends R>> transformer) {
        return userDao.existsById(id).flatMap(flag -> {
            if (flag) {
                return transformer.apply(value);
            }

            return Mono.empty();
        });
    }
}
